<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\GroupCreateRequest;
use App\Http\Requests\Admin\GroupUpdateRequest;
use App\Models\Admin\Group;
use App\Models\Admin\Role;
use Auth;
use Illuminate\Http\Request;

class GroupController extends Controller
{
    protected $fields = [
        'name'        => '',
        'description' => '',
        'roles'       => [],
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start');
            $length               = $request->get('length');
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Group::count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Group::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%');
                })->count();
                $data['data'] = Group::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%');
                })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = Group::count();
                $data['data']            = Group::
                    skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }
        return view('admin.group.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = $this->fields;

        if (Auth::guard(config('inventory.base.guard'))->user()->level == 1) {
            $data['roleAll'] = Role::all()->toArray();
        } else {
            /**
             * 角色列表应该来自用户有的角色 和 用户有的角色组
             */
            //分配人的角色
            $arrTempRoles = Auth::guard(config('inventory.base.guard'))->user()->roles->pluck('id')->toArray();
            //分配人的角色组
            $arrTempGroups = Auth::guard(config('inventory.base.guard'))->user()->groups->pluck('id')->toArray();
            $arrGroupRoles = Role::whereHas('groups', function ($query) use ($arrTempGroups) {
                $query->whereIn('group_id', $arrTempGroups);
            })->pluck('id')->toArray();

            // array_unique(array_merge_recursive($arrGroupRoles, $arrTempRoles));
            $data['roleAll'] = Role::all()->whereIn('id', array_unique(array_merge_recursive($arrGroupRoles, $arrTempRoles)))->toArray();
        }
        return view('admin.group.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param GroupCreateRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(GroupCreateRequest $request)
    {
        $group = new Group();

        foreach (array_keys($this->fields) as $field) {
            $group->$field = $request->get($field);
        }
        unset($group->roles);
        $group->save();

        if (is_array($request->get('roles'))) {
            $group->roles()->sync($request->get('roles', []));
        }

        event(new \App\Events\userActionEvent('\App\Models\Admin\group', $group->id, 1, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}添加用户组" . $group->name . "{" . $group->id . "}"));
        return redirect('/admin/group')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $group = Group::find($id);
        if (!$group) {
            return redirect('/admin/group')->withErrors("找不到该用户组!");
        }

        if (Auth::guard(config('inventory.base.guard'))->user()->level == 1) {
            $data['roleAll'] = Role::all()->toArray();
        } else {
            /**
             * 角色列表应该来自用户有的角色 和 用户有的角色组
             */
            //分配人的角色
            $arrTempRoles = Auth::guard(config('inventory.base.guard'))->user()->roles->pluck('id')->toArray();
            //分配人的角色组
            $arrTempGroups = Auth::guard(config('inventory.base.guard'))->user()->groups->pluck('id')->toArray();
            $arrGroupRoles = Role::whereHas('groups', function ($query) use ($arrTempGroups) {
                $query->whereIn('group_id', $arrTempGroups);
            })->pluck('id')->toArray();
            $data['roleAll'] = Role::all()->whereIn('id', array_unique(array_merge_recursive($arrGroupRoles, $arrTempRoles)))->toArray();
        }
        //该用户有的角色
        $data['roles']       = $group->roles->pluck('id')->toArray();
        $data['name']        = $group->name;
        $data['description'] = $group->description;
        $data['id']          = (int) $id;

        return view('admin.group.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param GroupUpdateRequest|Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(GroupUpdateRequest $request, $id)
    {
        $group = Group::find($id);
        if (!$group) {
            return redirect('/admin/group')->withErrors("找不到该用户组!");
        }

        foreach (array_keys($this->fields) as $field) {
            $group->$field = $request->get($field);
        }
        unset($group->roles);
        $group->save();

        $group->roles()->sync($request->get('roles', []));

        event(new \App\Events\userActionEvent('\App\Models\Admin\group', $group->id, 3, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}编辑用户组" . $group->name . "{" . $group->id . "}"));
        return redirect('/admin/group')->withSuccess('修改成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $group = Group::find($id);
        if (!$group) {
            return redirect('/admin/group')->withErrors("找不到该用户组!");
        }
        $group->users()->detach();
        $group->roles()->detach();

        if ($group) {
            $group->delete();
        } else {
            return redirect()->back()
                ->withErrors("删除失败");
        }

        event(new \App\Events\userActionEvent('\App\Models\Admin\group', $group->id, 2, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}删除组" . $group->name . "{" . $group->id . "}"));

        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
